package com.dopper.ws;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.List;
import java.util.Map;

import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * description:
 * @author jincarry
 * @date 2019-07-10 22:03
 */
public abstract class AbstractWebsocket implements Websocket {

    /**
     * 发送文本消息
     *
     * @param channel channel
     * @param msg msg
     */
    protected void sendMsg(Channel channel, String msg) {
        channel.writeAndFlush(new TextWebSocketFrame(msg));
    }

    /**
     * 发送二进制数据
     *
     * @param channel channel
     * @param msg msg
     */
    protected void sendMsg(Channel channel, byte[] msg) {
        channel.writeAndFlush(new BinaryWebSocketFrame(Unpooled.wrappedBuffer(msg)));
    }

    /**
     * 发送pong响应消息
     *
     * @param channel channel
     */
    protected void sendPong(Channel channel) {
        channel.writeAndFlush(new PongWebSocketFrame());
    }

    /**
     * 发送ping消息
     *
     * @param channel channel
     */
    protected void sendPing(Channel channel) {
        channel.writeAndFlush(new PingWebSocketFrame());
    }

    /**
     * 拒绝连接
     *
     * @param channel channel
     */
    protected void rejectConnection(Channel channel) {
        channel.writeAndFlush(new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)).addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void onPing(Channel channel) {
        sendPong(channel);
    }

    @Override
    public void onPong(Channel channel) {
        sendPing(channel);
    }

    @Override
    public void onOpen(Channel channel, Map<String, String> headers, Map<String, List<String>> queryString) {

    }

    @Override
    public void onMsg(Channel channel, String content) {

    }

    @Override
    public void onMsg(Channel channel, byte[] bytes) {

    }

    @Override
    public void onClose(Channel channel) {

    }

    @Override
    public void onError(Channel channel, Throwable throwable) {

    }
}
